#pragma once
#include <iostream>
#include <unordered_map>
#include <fstream>
#include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>
#include <unistd.h>
#include "Log.hpp"
#include "INETADDR.hpp"
using namespace std;
string dpath = "./Dictionary.txt";
string separator = " ";
class Dictionary
{
public:
    Dictionary(string path = dpath)
        : _path(path)
    {
    }
    bool LoadDictionary()
    {
        fstream in(_path);
        if (!in.is_open())
        {
            LOG(LogLevel::ERROR) << "打开字典失败";
            return false;
        }
        string input;
        while (getline(in, input))
        {
            auto pos = input.find(separator);
            if (pos == string::npos)
            {
                LOG(LogLevel::ERROR) << "加载字典失败";
                continue;
            }
            string English = input.substr(0, pos);
            string Chinese = input.substr(pos + separator.size());
            _dictionary.insert({English,Chinese});
            LOG(LogLevel::INFORMATION) << "加载字典成功: " << English << " -> " << Chinese;
        }
        in.close();
        return true;
    }
    string Translate(const string& word, INETADDR& client)
    {
        auto iter = _dictionary.find(word);
        if(iter != _dictionary.end())
        {
            LOG(LogLevel::INFORMATION) << client.StringAddr() << " " << iter->first << " -> " << iter->second;
            return iter->second;
        }
        else
            LOG(LogLevel::ERROR) << client.StringAddr() << " 字典不包含该单词";
       return "NONE";

    }
    ~Dictionary()
    {
    }

private:
    string _path;
    unordered_map<string, string> _dictionary;
};